<template>
  <i-table
      ref="dragable"
      :columns="columns"
      :data="values"
      highlight-row
      @on-selection-change="onSelectionChange"
      border
  ></i-table>
</template>

<script>
import Sortable from 'sortablejs'

export default {
  name: 'DragableTable',
  props: {
    columns: Array,
    values: Array
  },
  methods: {
    startFunc(e) {
      this.$emit('on-start', e.oldIndex)
    },
    endFunc(e) {
      let movedRow = this.values[e.oldIndex]
      this.values.splice(e.oldIndex, 1)
      this.values.splice(e.newIndex, 0, movedRow)
      this.$emit('on-end', {
        values: this.values,
        from: e.oldIndex,
        to: e.newIndex
      })
    },
    chooseFunc(e) {
      this.$emit('on-choose', e.oldIndex)
    },
    onSelectionChange(selection) {
      this.$emit('on-selection-change', selection)
    }
  },
  mounted() {
    var el = this.$refs.dragable.$children[1].$el.children[1]
    let vm = this
    Sortable.create(el, {
      onStart: vm.startFunc,
      onEnd: vm.endFunc,
      onChoose: vm.chooseFunc
    })
  }
}
</script>
